<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-el-icon-bottom" plain v-if="permission.workshop_delete" @click="handleDelete">数据导出</el-button>
      </template> -->
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="" slot="productPartNoSearch">
        <el-input placeholder="请选择 产品编码" readonly="true" v-model="search.productPartNo">
          <el-button slot="append" icon="el-icon-search" @click="openPartNoCommonModal"></el-button>
        </el-input>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/statistics/feeding/page" :option="option" :page="page" :query="query" file-name="上料记录"> </export-comp>
  </basic-container>
</template>

<script>
import { getList } from '@/api/report/loading-record-query';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList as getProductionLineList } from '@/api/product/productionline';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
export default {
  name: 'AdminWorkshop',
  components: {
    CommonModalTemplate,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'LOADING_RECORD_QUERY',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 100,
        searchLabelWidth: 90,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        columnBtn: false,
        menu: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 1
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchOrder: 4
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '上料工序',
            prop: 'routeName'
          },
          {
            label: '产线',
            prop: 'lineId',
            search: true,
            searchOrder: 3,
            type: 'select',
            dicData: []
          },
          {
            label: '原材料包装条码',
            prop: 'packNo',
            search: true,
            searchOrder: 2,
            searchLabelWidth: 130
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '包装数量',
            prop: 'quantity'
          },
          {
            label: '供应商名称',
            prop: 'partnerName'
          },
          {
            label: '操作人',
            prop: 'operatorName'
          },
          {
            label: '上料时间',
            prop: 'createTime',
            search: true,
            searchSpan: 8,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            defaultTime: ['00:00:00', '23:59:59'],
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            searchRules: [
              {
                required: true,
                message: '请选择上料时间',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
    let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
    startDate = startDate + ' ' + '00:00:00';
    endDate = endDate + ' ' + '23:59:59';
    this.$set(this.search, 'createTime', [startDate, endDate]);
    this.query.createTime = this.search.createTime;
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    const column = this.findObject(this.option.column, 'lineId');
    column.dicData = [];
    getProductionLineList(1, 10000, {})
      .then((res) => {
        column.dicData = this._get(res, 'data.data.records', []);
        column.dicData = this._map(column.dicData, (item) => {
          return {
            label: item.name,
            value: item.id
          };
        });
      })
      .catch((err) => {
        column.dicData = [];
      });
  },
  methods: {
    searchReset() {
      this.query = {};
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.createTime) {
        this.query.createTimeStart = this.$moment(this.query.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        this.query.createTimeEnd = this.$moment(this.query.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTime;
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },

    viewDetail(row) {
      this.showDialog = true;
      this.testDataDetail = row;
      this.testDataDetailResult = [];
      getDetail(row.id).then(
        (res) => {
          if (res.data && res.data.data) {
            this._forEach(res.data.data, (item) => {
              if (item.resultJson) {
                this.testDataDetailResult.push({
                  testDataDetailResult: JSON.stringify(JSON.parse(item.resultJson), null, '\t')
                });
              } else {
                this.testDataDetailResult.push({
                  testDataDetailResult: ''
                });
              }
            });
          } else {
            this.testDataDetailResult = [];
          }
        },
        (error) => {
          this.testDataDetailResult = [];
        }
      );
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    openPartNoCommonModal() {
      this.modalName = 'partNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'userModal':
          this.search.operatorName = this._get(rowData, 'realName', '');
          break;
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          this.search.productPartNo = this._get(rowData, 'partNo', '');
          break;
        case 'partNoModal':
          this.search.productPartNo = this._get(rowData, 'partNo', '');
          break;
      }
    }
  }
};
</script>

<style></style>
